package admin.subject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.CommonUtil;
import com.common.EmiJsonObj;
import com.common.ResultData;
import com.filter.BaseController;
import com.intercepter.AuthPassport;

import beans.subject.subinfo;
import beans.subject.subsetquestion;
import beans.subject.subsetquestionsubject;
import beans.sys.UserBean;
import service.subject.SubInfoServiceImpl;
import service.subject.SubSetQuestionImpl;
import service.subject.SubSetQuestionSubjectImpl;
@Controller
@RequestMapping("/setquestionsubject")
public class SetquestionSubjectController  extends BaseController{
	@Resource
	private SubInfoServiceImpl<subinfo> subInfoServiceImpl;
	
	@Resource
	private SubSetQuestionImpl<subsetquestion> _SubSetQuestionImpl;

	@Resource
	private SubSetQuestionSubjectImpl<subsetquestionsubject> _SubSetQuestionSubjectImpl;
	
	@AuthPassport(actionName="index",controllerName="special")
	@RequestMapping("/index")
	public String Index(String id) {
		//章节信息
		subsetquestion subsetquestion = null;
		try {
			subsetquestion = _SubSetQuestionImpl.queryById(id);
			List<subinfo> subList = subInfoServiceImpl.getByDriverAndSpecial(subsetquestion.getDrivertype(),subsetquestion.getSubtype());
			List<subsetquestionsubject> subsetquestionsubjectList = _SubSetQuestionSubjectImpl.getBySubSetId(id);
			
			List<Map> funTrees = new ArrayList<Map>();
			for(subinfo obj : subList){
				Map<String,Object> row = new HashMap<>();
				row.put("userid", obj.getId());
				row.put("checked", checkHas(subsetquestionsubjectList,row.get("userid").toString()));
				row.put("question", obj.getQuestion());
				funTrees.add(row);
			}
			getReq().setAttribute("funTrees", EmiJsonObj.fromArray(funTrees).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		getReq().setAttribute("subsetquestion", subsetquestion);
		
		return "admin/setquestion/subjectindex";
	}
	
	@AuthPassport(actionName="index",controllerName="special")
	@RequestMapping("/save")
	@ResponseBody
	public void save(String sqid,String ids) {
		String[] idsInfo = ids.split(",");
		try {
			_SubSetQuestionSubjectImpl.save(sqid,idsInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ResultData<String> rd = new ResultData<>();
		rd.setType(1);
		rd.setMessage("保存成功");
		responseJson(rd);
	}
	
	private int checkHas(List<subsetquestionsubject> subsetquestionsubjectList,String menuid){
		int bo = 0;
		for(subsetquestionsubject obj : subsetquestionsubjectList){
			if(obj.getSubid().equals(menuid)){
				bo = 1;
				break;
			}
		}
		return bo;
	}
}
